<?php

namespace App\Services;

use App\Models\Ding;
use App\Models\User;
use EasyDingTalk\Application;

class DingSendMessageService
{

    public function getDingApp(string $corp_id): Application
    {
        $ding = Ding::query()->where('corp_id', $corp_id)->first();
        return new Application(array_merge(config('ding'), $ding->toArray()));

    }


    /**
     * 统一发送消息的地方
     * @param User $user
     * @param Ding $ding
     * @param string $content
     */
    protected function send(User $user, Ding $ding, string $content)
    {
        $app = $this->getDingApp($ding->corp_id);
        $app->robot->singleMsg([
            'msgKey' => 'sampleText',
            'msgParam' => json_encode(['content' => $content]),
        ], $user->userid);
    }

    //分配客户时候的通知
    public function allocateCustomer(int $user_id)
    {
        if (!config('ding.robot_push')) {
            return;
        }
        $user = User::query()->with('ding')->where('id', $user_id)->first();
        if ($user) {
            $content = '有新的客户分配给您，请及时登录系统查看';
            $this->send($user, $user->ding, $content);
        }
    }


    /**
     * 有客户转交时，发送通知
     * @param int $user_id 员工id
     */
    public function transfer(int $user_id)
    {
        if (!config('ding.robot_push')) {
            return;
        }
        $user = User::query()->findOrFail($user_id);
        $content = '有新的客户转交给您，请及时登录系统查看';
        $this->send($user, $user->ding, $content);
    }


    //开通后台的通知
    public function openAdmin(int $user_id)
    {
        if (!config('ding.robot_push')) {
            return;
        }
        $user = User::query()->findOrFail($user_id);
        $url = config('app.url') . '/' . config('admin.route.prefix');
        $password = config('admin.default_password');
        $name = $user->phone;
        $content = <<<STR
管理员已为您开通后台，登录后请修改默认密码
登录地址：$url
账号：$name
密码：$password
STR;
        $this->send($user, $user->ding, $content);
    }
}
